<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
require_once "objetos/Usuario.php";
require_once "objetos/Email.php";
require_once "server/EmailServer.php";

session_start();
if(!array_key_exists("userId", $_SESSION) && $_SESSION["userId"] == NULL){
    head("Location: ../index.php");
}
$userId = $_SESSION["userId"];
$idEmail = $_GET["idEmail"];

$emailServer = new EmailServer();
if(array_key_exists("enviado", $_GET)){
    $conn = $emailServer->imapOpenOutBox($userId->getLogin(), $userId->getSenha());
    $emailHeader = imap_headerinfo($conn, $idEmail);
}else{
    $conn = $emailServer->imapOpen($userId->getLogin(), $userId->getSenha());
}
$emailImapHeader = $emailServer->obterInfoEmail($conn, $idEmail);
$emailImapContent = $emailServer->obterConteudoEmail($conn, $idEmail);

$resultFlag = imap_setflag_full($conn, $idEmail, "\Seen");

$email = new Email();
$email->setId($idEmail);
$email->setAssunto($emailImapHeader[0]->subject);
$from = explode('"',$emailImapHeader[0]->from);
$email->setRemetente($from[1]);

if(array_key_exists("enviado", $_GET)){
    $email->setDataEnviado($emailHeader->MailDate);
}else{
    $email->setDataRecebido($emailImapHeader[0]->date);
}

$email->setStatus($emailImapHeader[0]->seen);
$email->setConteudo($emailImapContent);

$emailServer->imapClose($conn);

$_SESSION["email"] = $email;
header("Location: ../paginas/verEmail.php");

?>

